#!/usr/bin/env python3
"""
调试ChromaDB查询结果结构
"""

def debug_chroma_query():
    """
    调试ChromaDB查询结果
    """
    print("=" * 50)
    print("调试ChromaDB查询结果")
    print("=" * 50)
    
    try:
        import chromadb
        from rag.boss_file.text_embedding import TextEmbedding
        
        # 连接ChromaDB
        client = chromadb.PersistentClient(path="./chromadb_db")
        collection_name = "job_text_embedding_0927"
        
        try:
            collection = client.get_collection(name=collection_name)
            print(f"✓ 成功获取集合: {collection_name}")
        except Exception as e:
            print(f"✗ 获取集合失败: {str(e)}")
            return
        
        # 生成查询向量
        text_embedding = TextEmbedding()
        query_text = "Python开发工程师"
        query_embedding = text_embedding.generate_embeddings([query_text])[0]
        print(f"✓ 生成查询向量，维度: {len(query_embedding)}")
        
        # 执行查询
        query_params = {
            "query_embeddings": [query_embedding],
            "n_results": 5,
            "include": ["metadatas", "documents", "distances"]
        }
        
        print("执行ChromaDB查询...")
        results = collection.query(**query_params)
        
        # 分析结果结构
        print(f"\n查询结果类型: {type(results)}")
        print(f"查询结果键: {list(results.keys()) if isinstance(results, dict) else 'Not a dict'}")
        
        if isinstance(results, dict):
            for key, value in results.items():
                print(f"\n{key}:")
                print(f"  类型: {type(value)}")
                if isinstance(value, list):
                    print(f"  长度: {len(value)}")
                    if len(value) > 0:
                        print(f"  第一个元素类型: {type(value[0])}")
                        if isinstance(value[0], list):
                            print(f"  第一个子列表长度: {len(value[0])}")
                        else:
                            print(f"  第一个元素: {value[0]}")
                else:
                    print(f"  值: {value}")
        
        # 检查是否有数据
        if results and results.get("ids"):
            ids = results["ids"]
            print(f"\nIDs结构: {type(ids)}, 长度: {len(ids)}")
            if len(ids) > 0:
                print(f"第一个ID列表: {ids[0]}")
                print(f"第一个ID列表长度: {len(ids[0])}")
            else:
                print("IDs列表为空")
        else:
            print("没有找到IDs")
            
    except Exception as e:
        print(f"调试过程出错: {str(e)}")
        import traceback
        traceback.print_exc()


def check_chroma_collections():
    """
    检查ChromaDB中的集合
    """
    print("\n" + "=" * 50)
    print("检查ChromaDB集合")
    print("=" * 50)
    
    try:
        import chromadb
        
        client = chromadb.PersistentClient(path="./chromadb_db")
        collections = client.list_collections()
        
        print(f"找到 {len(collections)} 个集合:")
        for collection in collections:
            print(f"  - {collection.name}")
            print(f"    元数据: {collection.metadata}")
            
    except Exception as e:
        print(f"检查集合失败: {str(e)}")


def main():
    """
    主函数
    """
    print("开始调试ChromaDB...")
    
    check_chroma_collections()
    debug_chroma_query()
    
    print("\n" + "=" * 50)
    print("调试完成！")
    print("=" * 50)


if __name__ == "__main__":
    main()
